# -*- coding: utf-8 -*-

class DBConnect
  
  def initialize(host, user, pass, database)
  
    open(host, user, pass, database)
  
  end
  
  def open(host, user, pass, database)
    
    @db = WIN32OLE.new("ADODB.Connection")
    @db.Open("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=#{database}")
    
  end
  
  def close()
    
    @db.Close()
    
  end
  
  def query(sql)
    
    #print "#{sql}<br />"
    return sql2array(sql)
    
  end
  
  def exec(sql)
    
    @db.Execute(sql)
    
  end
  
  def sql2array(sql)
    
    rs = WIN32OLE.new("ADODB.Recordset")
    rs.Open(sql, @db)
    
    i = 0
    values = []
    
    until rs.EOF
      
      val = {}
      
      0.upto rs.Fields.Count-1 do |j|
        val[rs.Fields(j).Name] = rs.Fields(j).Value
        #print "#{rs.Fields(j).Name} = #{val[j]}<br />"
      end
      
      values[i] = val
      i += 1
      
      rs.MoveNext()
      
    end
    
    rs.Close()
    return values
    
  end
  
  def list_fields(table)
    
    fields = []
    
=begin
    i = 0
    rs = @db.OpenSchema(4)
    until rs.EOF
      
      if rs.Fields("TABLE_NAME").Value == table
        fields[i] = rs.Fields("COLUMN_NAME").Value
        i += 1
      end
      
      rs.MoveNext()
      
    end
=end
    
    rs = WIN32OLE.new("ADODB.Recordset")
    rs.Open(table, @db)
    
    0.upto rs.Fields.Count-1 do |j|
      fields[j] = rs.Fields(j).Name
      #print "#{rs.Fields(j).Name} = #{val[j]}<br />"
    end
    
    rs.Close()
    return fields
    
  end
  
  def escape_string(str)
    #val = @db.escape_string(str.to_s)
    str = str.gsub("'", "''")
    return str
  end
  
end
